<template>
  <el-autocomplete
    class="inline-input w100"
    :disabled="disabled"
    :value="value"
    :key="name"
    @input="onInput"
    :name="name"
    @blur="onBlur"
    :fetch-suggestions="querySearch"
    :placeholder="placeholder"
    @select="handleSelect"
  ></el-autocomplete>
</template>

<script>
export default {
  props: {
    // 当前存在list下的key
    name: {
      type: String
    },
    value: {
      require: true
    },
    placeholder: {
      type: String,
      default: "请输入"
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {};
  },
  methods: {
    // 失去焦点
    onBlur() {
      if (this.value) {
        setTimeout(() => {
          this.$store.commit("autocomplete/setList", {
            name: this.name,
            value: this.value
          });
        }, 500);
      }
    },
    querySearch(queryString, cb) {
      var restaurants = this.$store.state.autocomplete.autocompleteList[
        this.name
      ]
        ? this.$store.state.autocomplete.autocompleteList[this.name]
        : [];
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    onInput(e) {
      this.$emit("input", e);
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    handleSelect(item) {
      this.$emit("input", item.value);
    }
  }
};
</script>

<style></style>
